package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.common.utils.uuid.UUID;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import lombok.extern.slf4j.Slf4j;
import lombok.extern.slf4j.XSlf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 设备表Service业务层处理
 * 
 * @author alexis
 * @date 2025-09-14
 */
@Service
@Slf4j
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient iotdaClient;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询设备表
     * 
     * @param id 设备表主键
     * @return 设备表
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备表列表
     * 
     * @param device 设备表
     * @return 设备表
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备表
     * 
     * @param device 设备表
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return deviceMapper.insert(device);
    }

    /**
     * 修改设备表
     * 
     * @param device 设备表
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return deviceMapper.updateById(device);
    }

    /**
     * 批量删除设备表
     * 
     * @param ids 需要删除的设备表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备表信息
     * 
     * @param id 设备表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return deviceMapper.deleteById(id);
    }

    @Override
    public void syncProductList() {
        ListProductsRequest request = new ListProductsRequest();
        request.setLimit(50);
        ListProductsResponse response = iotdaClient.listProducts(request);
        log.info("同步产品列表成功:{}", response);
        int code = response.getHttpStatusCode();
        if (code != 200){
            throw new RuntimeException("同步产品列表失败");
        }
        List<ProductSummary> products = response.getProducts();
        //存入redis
        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST, JSONUtil.toJsonStr(products));
    }

    @Override
    public List<ProductVo> allProduct() {
        String str = (String) redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST);
        if (StringUtils.isEmpty(str)){
            return new ArrayList<>();
        }
        List<ProductVo> list = JSONUtil.toList(str, ProductVo.class);
        return list;
    }

    @Override
    public void registerDevice(DeviceDto dto) {
        //位置类型0：老人 1：固定设备
        if(dto.getLocationType() == 0){
            dto.setDeviceDescription(String.valueOf(dto.getBindingLocation()));
            dto.setPhysicalLocationType(-1);
        }

        //1.判断设备名称是否重复
        Device device = deviceMapper.selectOne(new LambdaQueryWrapper<Device>()
                .eq(Device::getDeviceName, dto.getDeviceName()));
        if(device != null){
            throw new ServiceException("设备名称重复！");
        }
        //2.判断设备标识码是否重复
        device = deviceMapper.selectOne(new LambdaQueryWrapper<Device>()
                .eq(Device::getNodeId, dto.getNodeId()));
        if(device != null){
            throw new ServiceException("设备标识码重复！");
        }
        //3.校验同一位置是否绑定了同一产品【数据库有唯一约束，可以走异常处理器】
        device = deviceMapper.selectOne(new LambdaQueryWrapper<Device>()
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getProductKey, dto.getProductKey())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(Device::getPhysicalLocationType, dto.getPhysicalLocationType())
        );

        if(device != null){
            throw new ServiceException("同一位置只能绑定一个产品！");
        }

        //4.调用华为云的SDK，向iot中新增设备
        AddDeviceRequest request = new AddDeviceRequest();

        AddDevice body = new AddDevice();
        body.withProductId(dto.getProductKey());
        body.withDeviceName(dto.getDeviceName());
        body.withNodeId(dto.getNodeId());

        AuthInfo authInfobody = new AuthInfo();
        String secret = UUID.randomUUID().toString().replace("-", "");
        authInfobody.withSecret(secret);
        body.setAuthInfo(authInfobody);

        request.setBody(body);
        AddDeviceResponse response = null;
        try{
            response = iotdaClient.addDevice(request);
        }catch(Exception e){
            throw new ServiceException("设备注册失败！");
        }

        int code = response.getHttpStatusCode();
        if(code !=201){
            throw new ServiceException("设备注册失败！");
        }
        //5.将数据保存到数据库
        device = new Device();
        //填充数据
        BeanUtils.copyBeanProp(device,dto);
        device.setIotId(response.getDeviceId());
        device.setSecret(secret);
        deviceMapper.insert(device);
    }

    @Override
    public DeviceDetailVo getDeciceDetail(String id) {
        DeviceDetailVo detail = new DeviceDetailVo();
        //1.查询华为云iot的设备数据
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.withDeviceId(String.valueOf(id));
        try {
            ShowDeviceResponse response = iotdaClient.showDevice(request);
            if (response.getHttpStatusCode() == 200){
                detail.setDeviceStatus(response.getStatus());
                if (response.getActiveTime()!= null) {
                    detail.setActiveTime(LocalDateTime.parse(response.getActiveTime(),
                            DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")));
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            detail.setDeviceStatus("获取华为云中设备列表失败");
        }


         //2.查询数据库设备数据
        Device device = deviceMapper.selectOne( new LambdaQueryWrapper<Device>()
                .eq(Device::getIotId, id));
        if (device == null){
            throw new BaseException("设备不存在");
        }
        BeanUtils.copyBeanProp(detail, device);

         return  detail;
    }
/**
     * 查询设备属性
     * @param iotId
     * @return
     */
    @Override
    public List<Map<String, Object>> queryServiceProperties(String iotId) {
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);
        ShowDeviceShadowResponse response = iotdaClient.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200){
            throw new BaseException("查询设备属性失败");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        if (CollUtil.isNotEmpty( shadow)){
            DeviceShadowProperties reported = shadow.get(0).getReported();
            String eventTime = reported.getEventTime();
            Map<String,Object> properties = (Map<String,Object>) reported.getProperties();
            if (CollUtil.isNotEmpty( properties)){
                List collect = properties.entrySet().stream().map(new Function<Map.Entry, Map>() {
                    @Override
                    public Map apply(Map.Entry entry) {
                        Map<String, Object> map = new HashMap();
                        map.put("evenTime", eventTime);
                        map.put("functionId", entry.getKey());
                        map.put("value", entry.getValue());

                        return map;
                    }
                }).collect(Collectors.toList());
                return collect;
            }
        }
        return new ArrayList<>();
    }
    /**
     * 修改设备信息
     * @param device
     */

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDeviceById(Device device) {
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.withDeviceId(device.getIotId());
        UpdateDevice body = new UpdateDevice();
        body.withDeviceName(device.getDeviceName());
        request.withBody(body);
        UpdateDeviceResponse response = iotdaClient.updateDevice(request);
        if (response.getHttpStatusCode() != 200){
            throw new BaseException("修改设备信息失败");
        }
        deviceMapper.updateById(device);
    }
    /**
     * 删除设备
     * @param iotId
     */
    @Override
    public void deleteDeviceByIotId(String iotId) {
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(iotId);
        DeleteDeviceResponse response = iotdaClient.deleteDevice(request);
        if (response.getHttpStatusCode() != 204){
            throw new BaseException("删除设备失败");
        }
        Device device = deviceMapper.selectOne(new LambdaQueryWrapper<Device>()
                .eq(Device::getIotId, iotId));

        if (device != null) {
            deviceMapper.deleteById(device.getId());
        }else {
            throw new BaseException("设备不存在");
        }

    }

    @Override
    public List<ServiceCapability> queryProduct(String productKey) {
        ShowProductRequest request = new ShowProductRequest();
        request.withProductId(productKey);
        ShowProductResponse response = iotdaClient.showProduct(request);
        if (response.getHttpStatusCode() == 200){
            return response.getServiceCapabilities();
        }
        return null;
    }

    @Override
    public List<Long> getNursingIdByyiotId(String iotId) {
        return deviceMapper.selectNursingIdByyiotId(iotId);
    }
}
